package com.wuda.servlet;

import com.wuda.bean.Book;
import com.wuda.bean.BookReview;
import com.wuda.dao.BookDao;
import com.wuda.dao.BookReviewDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/bookDetailById")
public class BookDetail extends HttpServlet {

	private final BookDao bookDao = new BookDao();


	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("application/json; charset=utf8");

		String id = req.getParameter("id");
		JSONObject jsonResult = new JSONObject();
		int code = 500;
		String msg = "无数据";
		JSONObject bookData = new JSONObject();

		try {
			int bookId = Integer.parseInt(id);
			Book book = bookDao.getBookById(bookId);
			if (book != null) {
				bookData.put("book_id", book.getBookId());
				bookData.put("title", book.getTitle());
				bookData.put("author", book.getAuthor());
				bookData.put("isbn", book.getIsbn());
				bookData.put("publisher", book.getPublisher());
				bookData.put("publish_date", book.getPublishDate().toString());
				bookData.put("stock_quantity", book.getStockQuantity());
				bookData.put("type", book.getType());
				bookData.put("introduce", book.getIntroduce());


				// 添加评论信息
				JSONArray reviewsArray = new JSONArray();
				for (BookReview review : book.getReviews()) {
					JSONObject reviewData = new JSONObject();
					reviewData.put("review_id", review.getReviewId());
					reviewData.put("user_id", review.getUserId());
					reviewData.put("book_id", review.getBookId());
					reviewData.put("rating", review.getRating());
					reviewData.put("comment", review.getComment());
					reviewData.put("review_date", review.getReviewDate().toString());
					reviewData.put("user_name", review.getUser().getUsername());
					reviewData.put("user_email", review.getUser().getEmail());
					reviewData.put("user_role", review.getUser().getRole());
					reviewsArray.add(reviewData);
				}
				bookData.put("reviews", reviewsArray);

				code = 200;
				msg = "查询成功";
			}
		} catch (NumberFormatException e) {
			msg = "无效的书籍ID";
			e.printStackTrace();
		}

		jsonResult.put("code", code);
		jsonResult.put("msg", msg);
		jsonResult.put("data", bookData);

		try (PrintWriter out = resp.getWriter()) {
			out.print(jsonResult);
			out.flush();
		}
	}
}
